import pyautogui
import pyperclip
from datetime import datetime
# from printutil import *
import pymysql
import os
import time
from apscheduler.schedulers.blocking import BlockingScheduler


order_list = []


class orderOBJ:
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"


# 微信发消息
def send_msg(msg):
    entry_position = pyautogui.Point(x=783, y=885)  # 输入框位置
    pyautogui.click(entry_position)
    pyperclip.copy(msg)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter')


# 打开QQ，然后打开通知群
def open_wx():
    pyautogui.hotkey('win', 'd')
    time.sleep(1)
    pyautogui.PAUSE = 1  # 设置每步操作间隔
    pyautogui.hotkey('alt', 'z')

    print(pyautogui.position())  # 打印坐标
    # 家里
    icon_position = pyautogui.Point(x=113, y=44)  # 搜索输入框位置
    # 公司
    # icon_position = pyautogui.Point(x=698, y=254)  # 输入框位置

    pyautogui.click(icon_position)
    pyperclip.copy('订单通知-晨夕小铺')
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.press('enter')


# 关闭微信窗口
def close_wx():
    pyautogui.hotkey('alt', 'z')


def add_db():
    # 打开数据库连接，不指定数据库
    # conn = pymysql.connect(host='localhost', port=3306, user='root', password='xuhuan.5130638')
    conn = pymysql.connect(host='139.155.88.162', port=3306, user='root', password='xuhuan.59')
    conn.select_db('linjiashop')
    cur = conn.cursor()  # 获取游标
    try:
        # print("===========================================================================================================")
        # print(jsonss)
        print("通知系统开始查询订单")
        cur.execute("select * from t_shop_order where status=2")  # 1未付款 2未发货 3已发货 4已完成
        data = cur.fetchall()
        # 这里面有未通知的订单才打开微信
        # isOpenWx = False
        # if data:
        #     for row in data:
        #         if row[13] not in order_list:
        #             open_wx()
        #             isOpenWx = True
        #             break

        if data:
            for row in data:
                haveOrder = False
                # 判断是否处理过这个订单
                for item in order_list:
                    if item.id == row[13]:
                        haveOrder = True
                        break

                if haveOrder:
                    print("已经处理了当前订单不重复通知")
                else:

                    # 添加数据
                    order = orderOBJ()
                    order.id = row[13]
                    order.title = "订单号:"+str(row[13]) + "\n手机号:"+str(row[12]) + "\n地址："+str(row[6])+"\n订单备注:"+str(row[11])+"\n下单时间:"+str(row[1])
                    order.notify = True
                    order.direction = ""

                    # order_list.append(str(row[13]))
                    # send_msg("订单号:"+str(row[13])
                    #          + "\n手机号:"+str(row[12])
                    #          + "\n地址："+str(row[6]))
                    # 查询订单商品列表
                    cur.execute("select * from t_shop_order_item where id_order="+str(row[0]))
                    order_item_list = cur.fetchall()
                    for row_item in order_item_list:
                        # 这里只能拿到商品id，需要去拿商品名称
                        # print(row_item + "购买数量:"+str(row_item[3]))
                        # 查询商品名称
                        cur.execute("select * from t_shop_goods where id=" + str(row_item[4]))
                        goods = cur.fetchone()
                        if row_item[6] is None:
                            # 单规格商品
                            # send_msg("名称:" + str(goods[14]) + "  数量:" + str(row_item[3]))

                            order.direction = order.direction + "名称:" + str(goods[14]) + "  数量:" + str(row_item[3]) + "\n"
                        else:
                            cur.execute("select * from t_shop_goods_sku where id=" + str(row_item[6]))
                            sku = cur.fetchone()
                            # send_msg("名称:" + str(goods[14])+"  "+str(sku[6]) + "  数量:" + str(row_item[3]))
                            order.direction = order.direction + "名称:" + str(goods[14])+"  "+str(sku[6]) + "  数量:" + str(row_item[3]) + "\n"
                            # 多规格需要查询规格名称
                    order_list.append(order)
                    # 订单通知之后自动发货
                    # sql = "update t_shop_order set id_express='1',shipping_amount='0',shipping_sn='1111234',status='3' where " \
                    #       "id='{}'".format(str(row[0]))
                    # cur.execute(sql)

        # if isOpenWx:
        #     close_wx()
        conn.commit()
    finally:
        try:
            cur.close()
            conn.close()
        except Exception as e1:
            print('sql执行成功异常：' + str(e1))


def task():
    # print_()
    add_db()
    print("开始处理订单是否需要通知:--->"+str(time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())))
    print("待通知订单数量:"+str(len(order_list)))
    for item in order_list:
        print("===当前订单状态:"+str(item.notify) + "订单号：-->"+str(item.id) + "  " + str(item.title))
        if item.notify:
            open_wx()
            # send_msg(item.title)
            send_msg(item.title+"\n"+item.direction)
            item.notify = False
            close_wx()
            break


if __name__ == '__main__':
    # scheduler = BlockingScheduler()  # 实例化
    # scheduler.add_job(add_db, 'interval', seconds=90)  # 添加任务
    # scheduler.start()

    print("系统开始运行:"+str(time.strftime('%Y-%m-%d %H-%I-%S', time.localtime())))
    scheduler1 = BlockingScheduler()  # 实例化
    scheduler1.add_job(task, 'interval', seconds=60)  # 添加任务
    scheduler1.start()

    os.system("pause")

    # time.sleep(5)
    # print(pyautogui.position())  # 打印坐标